package com.jinzhi.jinzhidata.controller;

import com.jinzhi.jinzhidata.dataobject.*;
import com.jinzhi.jinzhidata.enums.ArticleStateEnum;
import com.jinzhi.jinzhidata.enums.ResultEnum;
import com.jinzhi.jinzhidata.service.*;
import com.jinzhi.jinzhidata.util.CookieUtil;
import com.jinzhi.jinzhidata.util.JwtUtil;
import com.jinzhi.jinzhidata.util.ResultVOUtil;
import com.jinzhi.jinzhidata.util.UUIDUtil;
import com.jinzhi.jinzhidata.vo.ListResourceVO;
import com.jinzhi.jinzhidata.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author vansl
 * @description
 * @date 2020-01-16 13:55
 **/
@RestController
@RequestMapping("/backend")
public class BackendController {

    @Autowired
    UserService userService;

    @Autowired
    ArticleService articleService;

    @Autowired
    ArticleContentService articleContentService;

    @Autowired
    ArticleTypeService articleTypeService;

    @Autowired
    ResourceService resourceService;

    @Autowired
    CarouselFigureService carouselFigureService;

    public boolean checkPermission(HttpServletRequest request, HttpServletResponse response) {
        String userId = JwtUtil.verifyAccessToken(request, response);
        if (userId == null) {
            return false;
        }
        User user = userService.selectUserByUserId(userId);
        if (user == null) {
            return false;
        }
        return "admin".equals(user.getUserRole());
    }

    @PostMapping("/login")
    public ResultVO login(@RequestBody User loginUser, HttpServletRequest request, HttpServletResponse response) {
        String userName = loginUser.getUserName();
        String password = loginUser.getUserPassword();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return ResultVOUtil.error(ResultEnum.WRONG);
        }
        User user = userService.selectUserByUserPhone(userName);
        if (user == null) {
            return ResultVOUtil.error(ResultEnum.USER_NOT_EXISTS);
        }
        System.out.println(user);
        if (!password.equals(user.getUserPassword())) {
            return ResultVOUtil.error(ResultEnum.WRONG);
        }
        if (!"admin".equals(user.getUserRole())) {
            return ResultVOUtil.error(ResultEnum.WRONG);
        }
        String token = JwtUtil.sign(user.getUserId(), "admin");
        CookieUtil.addCookie(response, "accessToken", token);
        Map<String, String> data = new HashMap<>();
        data.put("accessToken", token);
        return ResultVOUtil.success(data);
    }

    @GetMapping("/article/count")
    public ResultVO articleCount(HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        Long count = articleService.count();
        return ResultVOUtil.success(count);
    }

    @GetMapping("/article/list")
    public ResultVO articleList(Integer page, Integer size, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(page, size, sort);
        List<Article> articleList = articleService.selectArticleList(pageRequest);
        return ResultVOUtil.success(articleList);
    }

    @GetMapping("/article/{articleId}")
    public ResultVO articleDetail(@PathVariable String articleId, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        Article article = articleService.selectByArticleId(articleId);
        return ResultVOUtil.success(article);
    }

    @DeleteMapping("/article/{articleId}")
    public ResultVO deleteArticle(@PathVariable String articleId, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        articleService.deleteArticle(articleId);
        return ResultVOUtil.success();
    }

    @GetMapping("/articleType/list")
    public ResultVO articleTypeList(HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        List<ArticleType> articleTypeList = articleTypeService.selectArticleTypeList();
        return ResultVOUtil.success(articleTypeList);
    }

    @GetMapping("/articleContent/{articleContentId}")
    public ResultVO getArticleContent(@PathVariable String articleContentId, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        return ResultVOUtil.success(articleContentService.selectByArticleContentId(articleContentId));
    }


    @PostMapping("/article")
    public ResultVO saveArticle(@RequestBody Article article, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        if (StringUtils.isEmpty(article.getArticleId())) {
            String articleId = UUIDUtil.getUUID();
            article.setArticleId(articleId);
            article.setArticleState(ArticleStateEnum.PUBLISH.getCode());
            article.setArticleLikeNum(0);
            article.setArticleAuthorId(JwtUtil.verifyAccessToken(request, response));
        }
        return ResultVOUtil.success(articleService.saveArticle(article));
    }

    @PostMapping("/articleContent")
    public ResultVO saveArticleContent(@RequestBody ArticleContent articleContent, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        if (StringUtils.isEmpty(articleContent.getArticleContentId())) {
            String articleContentId = UUIDUtil.getUUID();
            articleContent.setArticleContentId(articleContentId);
        }
        return ResultVOUtil.success(articleContentService.saveArticleContent(articleContent));
    }


    @GetMapping("/resource/count")
    public ResultVO resourceCount(HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        Long count = resourceService.count();
        return ResultVOUtil.success(count);
    }

    @GetMapping("/resource/list")
    public ResultVO resourceList(Integer page, Integer size, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(page, size, sort);
        List<ListResourceVO> listResourceVOList = resourceService.selectResourceList(pageRequest);
        return ResultVOUtil.success(listResourceVOList);
    }

    @GetMapping("/resource/check")
    public ResultVO checkResource(String resourceId, String resourceState, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        return ResultVOUtil.success(resourceService.checkResource(resourceId, resourceState));
    }

    @GetMapping("/carouselFigure/count")
    public ResultVO countCarouselFigure(HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        return ResultVOUtil.success(carouselFigureService.count());
    }

    @PostMapping("/carouselFigure")
    public ResultVO saveCarouselFigure(@RequestBody CarouselFigure carouselFigure, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        if (StringUtils.isEmpty(carouselFigure.getCarouselFigureImage())){
            return ResultVOUtil.error(ResultEnum.IMAGE_EMPTY_ERROR);
        }
        if (StringUtils.isEmpty(carouselFigure.getArticleId())){
            return ResultVOUtil.error(ResultEnum.ARTICLE_EMPTY_ERROR);
        }
        Article article = articleService.selectByArticleId(carouselFigure.getArticleId());
        if (!article.getArticleState().equals(ArticleStateEnum.PUBLISH.getCode())) {
            return ResultVOUtil.error(ResultEnum.ARTICLE_DELETE_ERROR);
        }
        if (StringUtils.isEmpty(carouselFigure.getCarouselFigureId())){
            carouselFigure.setCarouselFigureId(UUIDUtil.getUUID());
        }
        return ResultVOUtil.success(carouselFigureService.save(carouselFigure));
    }

    @DeleteMapping("/carouselFigure/{carouselFigureId}")
    public ResultVO deleteCarouselFigure(@PathVariable String carouselFigureId, HttpServletRequest request, HttpServletResponse response) {
        if (!checkPermission(request, response)) {
            return ResultVOUtil.error(ResultEnum.PERMISSION_DENIED);
        }
        carouselFigureService.deleteById(carouselFigureId);
        return ResultVOUtil.success();
    }
}
